from flask import Flask, request, redirect, url_for, render_template
import mysql.connector
from docx import Document
import os

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'docx'}
app.secret_key = 'some_secret_key'  # 用于闪存消息

# 允许的文件类型
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']

def extract_questions(file_path, question_type):
    document = Document(file_path)
    questions = {
        'questionsxuanze': [],
        'question2': [],
        'questions': []
    }
    current_question = None

    for para in document.paragraphs:
        text = para.text.strip()

        if text.startswith("Q:") or text.startswith("Q:") and (text[2].isdigit()):  # 识别题目开始
            if current_question:
                if current_question['type']:
                    questions[current_question['type']].append(current_question)
            current_question = {
                'type': None,
                'text': text[2:].strip(),
                'options': {'A': None, 'B': None, 'C': None, 'D': None},
                'correct_answer': None,
                'answers': []
            }

        elif text.startswith("答案:") or text.startswith("Answer:"):  # 答案
            if current_question:
                current_question['correct_answer'] = text[7:].strip()

        elif any(option in text for option in ['A:', 'B:', 'C:', 'D:']):  # 选择题选项
            options = text.split(' ')
            for option in options:
                if option.startswith('A:'):
                    current_question['options']['A'] = option[2:].strip()
                elif option.startswith('B:'):
                    current_question['options']['B'] = option[2:].strip()
                elif option.startswith('C:'):
                    current_question['options']['C'] = option[2:].strip()
                elif option.startswith('D:'):
                    current_question['options']['D'] = option[2:].strip()

        elif text.startswith("答案:") and (text[3:].strip() in ['对', '错']):  # 判断题答案
            if current_question:
                current_question['correct_answer'] = text[3:].strip()

        elif text and (text[0].isdigit() and text[1] == '.'):  # 主观题
            if current_question:
                if current_question['type']:
                    questions[current_question['type']].append(current_question)
            current_question = {
                'type': 'questions',
                'text': text,
                'options': {'A': None, 'B': None, 'C': None, 'D': None},
                'correct_answer': None,
                'answers': []
            }

        elif text:
            if current_question['type'] == 'questions':
                current_question['answers'].append(text)

    if current_question:
        if current_question['type']:
            questions[current_question['type']].append(current_question)

    return questions

def insert_questions(exam_name, questions):
    conn = mysql.connector.connect(
        host="152.136.49.229",
        user="yuyu",
        password="123456",  # 替换为实际的数据库密码
        database="yuyude",
    )
    cursor = conn.cursor()

    try:
        # 插入试卷信息
        sql = "INSERT INTO exams (name) VALUES (%s)"
        cursor.execute(sql, (exam_name,))
        exam_id = cursor.lastrowid

        for q_type, qs in questions.items():
            for question in qs:
                if q_type == 'questionsxuanze':  # 选择题
                    sql = """
                    INSERT INTO questionsxuanze (exam_id, question_text, a, b, c, d, correct_answer)
                    VALUES (%s, %s, %s, %s, %s, %s, %s)
                    """
                    values = (
                        exam_id, question['text'],
                        question['options']['A'], question['options']['B'],
                        question['options']['C'], question['options']['D'],
                        question['correct_answer']
                    )
                elif q_type == 'question2':  # 判断题
                    sql = """
                    INSERT INTO question2 (exam_id, question_text, correct_answer)
                    VALUES (%s, %s, %s)
                    """
                    values = (exam_id, question['text'], question['correct_answer'])
                elif q_type == 'questions':  # 主观题
                    sql = """
                    INSERT INTO questions_and_answers (exam_name, question_text, answer_text)
                    VALUES (%s, %s, %s)
                    """
                    for answer in question['answers']:
                        values = (exam_name, question['text'], answer)
                        cursor.execute(sql, values)
                    continue

                cursor.execute(sql, values)

        conn.commit()
    except mysql.connector.Error as err:
        print(f"Error: {err}")
        conn.rollback()
    finally:
        cursor.close()
        conn.close()

@app.route('/')
def index():
    return render_template('upload.html')

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files or request.files['file'].filename == '':
        return '没有选择文件'

    file = request.files['file']
    question_type = request.form['question_type']

    if file and allowed_file(file.filename):
        filename = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(filename)

        if not os.path.exists(filename):
            return '文件保存失败'

        try:
            if question_type == 'all':
                questions = extract_questions(filename, question_type)
            else:
                questions = extract_questions(filename, question_type)
            print(f"提取的问题: {questions}")
        except Exception as e:
            return f'提取问题时发生错误: {e}'

        try:
            insert_questions('Sample Exam', questions)
        except Exception as e:
            return f'插入问题时发生错误: {e}'

        return redirect(url_for('upload_success'))

    return '文件格式不正确'

@app.route('/upload_success')
def upload_success():
    return render_template('success.html')  # 使用模板渲染成功页面

if __name__ == '__main__':
    if not os.path.exists(app.config['UPLOAD_FOLDER']):
        os.makedirs(app.config['UPLOAD_FOLDER'])
    app.run(host='0.0.0.0', port=5000, debug=True)
